package com.hb.application.service;

import com.google.common.collect.Sets;
import com.hb.core.enums.CommCode;
import com.hb.core.exception.ServiceException;
import com.hb.core.model.SecurityClient;
import com.hb.core.oauth2.AuthorizationServer;
import com.hb.domain.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @description:
 * @projectName: zhb-frame-build
 * @author: zhouhaizhi
 * @createTime: 2021/8/30 11:11
 * @version:1.0
 */
@Service
public class OAuthClientDetailService implements ClientDetailsService {

    @Value("${spring.application.name}")
    public String resourceId;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthorizationServer authorizationServer;

    @Override
    public ClientDetails loadClientByClientId(String clientName) throws ClientRegistrationException {
        SecurityClient securityClient = sysUserService.getSecurityClientByLoginName(clientName);
        if (null == securityClient) {
            throw new ServiceException(CommCode.PARAM_ERROE,"用户信息不存在");
        }
        if (securityClient.getInvalid() == Boolean.TRUE) {
            throw new ServiceException(CommCode.PARAM_ERROE,"该账号已被禁用");
        }

        BaseClientDetails details = new BaseClientDetails();
        details.setClientId(clientName);
        details.setResourceIds(Sets.newHashSet(resourceId));
        details.setScope(Sets.newHashSet("read","write"));
        details.setClientSecret(passwordEncoder.encode(securityClient.getPassword()));
        details.setAuthorizedGrantTypes(Sets.newHashSet("client_credentials","refreshToken","authorization_code"));
        details.setAccessTokenValiditySeconds(authorizationServer.accessTokenValiditySeconds);
        details.setRefreshTokenValiditySeconds(authorizationServer.refreshTokenValiditySeconds);
        details.setAuthorities(Collections.emptySet());
        details.setResourceIds(securityClient.getAud());

        return details;
    }
}
